<!-- 入库管理 -->
<template>
  <div class="app-container">
    <!-- 上部分表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="85px"
      class="globalSerchFormStyle"
      :rules="rules"
    >
      <el-row>
        <el-col :span="6" v-if="!['2'].includes($store.state.user.userLevel)">
          <el-form-item label="仓库/门店" prop="stationId" size="small">
            <el-select
              style="width: 180px"
              v-model="queryParams.stationId"
              :clearable="true"
              filterable
              placeholder="请选择仓库/门店"
            >
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批次" prop="batchNo" size="small">
            <el-input
              v-model="queryParams.batchNo"
              placeholder="请输入批次"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" size="small" prop="createTime">
            <el-date-picker
              v-model="createTime"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 180px"
              :default-time="['00:00:00', '23:59:59']"
              @change="createTimeChange"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row
      class="global_el_rowStyle"
      :gutter="10"
      style="
        border-top: none;
        border-bottom: 1px solid #f5f5f5;
        margin-top: 0px;
      "
    >
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="inquireList"
          >查询</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="InventoryEntryNewButton"
          plain
          >入库</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" plain @click="storageBulkButton"
          >批量入库</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleExport"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading"
      @selection-change="handleSelectChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column
        prop="stationName"
        label="仓库/门店"
        v-if="!['2'].includes($store.state.user.userLevel)"
      >
      </el-table-column>
      <el-table-column prop="batchNo" label="批次"> </el-table-column>
      <el-table-column prop="commodityNum" label="商品总数"> </el-table-column>
      <el-table-column prop="commodityPrice" label="商品总额">
      </el-table-column>
      <el-table-column prop="notes" label="备注"> </el-table-column>
      <el-table-column prop="createUser" label="创建员"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="80"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="tableViewClick(scope.row)"
            >查看</el-button
          >
          <el-button size="mini" type="text">打印</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="inquireList"
    />

    <!-- 查看 -->
    <el-dialog title="查看" :visible.sync="tableView">
      <el-table
        :data="gridData"
        border
        style="margin-bottom: 50px"
        max-height="712"
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column
          property="commodityName"
          label="商品名称"
        ></el-table-column>

        <el-table-column
          property="commodityCode"
          label="商品编码"
        ></el-table-column>

        <el-table-column
          property="barCode"
          label="商品条码"
          width="150"
        ></el-table-column>

        <el-table-column
          property="categoryName"
          label="商品分类"
        ></el-table-column>
        <el-table-column property="unit" label="单位"></el-table-column>
        <el-table-column
          property="inventoryQuantity"
          label="入库数量"
        ></el-table-column>
        <el-table-column property="salePrice" label="单价"></el-table-column>
        <el-table-column property="totalPrice" label="总价"></el-table-column>
      </el-table>
      <el-button
        type="primary"
        size="small"
        class="dialog-button"
        @click="downShut"
        >关闭</el-button
      >
    </el-dialog>

    <!-- 批量入库 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="450px"
      style="text-align: center"
    >
      <el-upload
        ref="upload"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :on-success="handleFileSuccess"
        :on-change="handleFileChange"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <span style="color: red">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </span>
          <el-link
            type="info"
            style="font-size: 12px; margin-bottom: 3px"
            @click="downloadButton"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="uploadLoading"
          size="small"
          >确 定</el-button
        >
        <el-button @click="cancellation" size="small">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量入库错误 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="fileUploadShow"
      width="45%"
      style="text-align: center"
    >
      <div class="dialog-table">
        <div style="margin-bottom: 30px">
          以下商品批量入库失败，请修改后再次提交。
        </div>
        <div class="tableInto-table">
          <el-table :data="tableInto" border>
            <el-table-column
              type="index"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column prop="barCode" label="商品条码" width="150">
            </el-table-column>
            <el-table-column prop="commodityName" label="商品名称">
            </el-table-column>
            <el-table-column prop="inventoryQuantity" label="入库数量">
            </el-table-column>
            <el-table-column prop="reason" label="失败原因" width="200">
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          plain
          @click="offUpload"
          size="small"
          round
          v-show="fileUploadShow"
        >
          关闭</el-button
        >
      </div>
    </el-dialog>

    <!-- 新增入库单 -->
    <InventoryEntryNew
      :newInventoryEntry.sync="newInventoryEntry"
    ></InventoryEntryNew>
  </div>
</template>
<script>
import { cloneDeep } from "lodash";
import {
  getRepositoryAndStation,
  batchExport,
  batchlist,
  warehouseList,
} from "@/api/nonOil/putlntoStorage";
import { timeComparison } from "@/utils/timeConversion";
import {} from "@/api/nonOil/putlntoStorage";
import InventoryEntryNew from "./InventoryEntry_new.vue";
import { getToken } from "@/utils/auth";
import request from "@/utils/request_oil";
export default {
  name: "PutIntoStorage",
  components: {
    InventoryEntryNew,
  },
  data() {
    return {
      fileUploadShow: false,

      // 批量入库失败表格
      tableInto: [],

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "批量入库",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_APIOIL + "/warehouse/export",
      },

      stationList: [],

      // 查看queryParamsenterpriseId
      tableView: false,
      // 新增入库单
      newInventoryEntry: false,
      // 批量入库
      uploadLoading: false,

      loading: false,
      total: 0,
      createTime: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginTime: null,
        endTime: null,
        batchNo: null,
        stationId: null,
        enterpriseId: null,
      },

      tableData: [],

      gridData: [],

      rules: {},

      selectionList: [],
    };
  },
  created() {
    this.inquireList();
    this.getStationList();
  },
  methods: {
    // 选中行
    handleSelectChange(selection) {
      this.selectionList = selection;
    },

    // 文件上传
    handleFileChange(event, file, fileList) {
      const fileDeep = cloneDeep(file);
      if (file.length > 1) {
        file.length = 0;
        file[0] = fileDeep[1];
      }
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code == 500) {
        if (response.data) {
          this.tableInto = response.data;
          this.fileUploadShow = true;
        }
        this.$message.error(response.msg);
      } else {
        this.$message.success("批量入库成功");
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.uploadLoading = false;
    },

    // 确认提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 取消上传退出
    cancellation() {
      this.upload.open = false;
      this.$refs.upload.abort();
      this.$refs.upload.clearFiles();
      this.$message("已取消文件导入");
    },

    // 点击批量入库模版下载
    async downloadButton() {
      let res = await request.get("/warehouse/template", {
        responseType: "blob",
        withCredentials: false,
      });
      const fileExt = "xlsx";
      const filename = "导入模版" + (fileExt ? "." + fileExt : "");
      const blob = new Blob([res]);
      var downloadElement = document.createElement("a");
      var href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = filename;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    },

    // 关闭查看
    downShut() {
      this.tableView = false;
    },

    // 点击查看
    tableViewClick(row) {
      this.tableView = true;
      warehouseList({ batchId: row.id }).then((res) => {
        this.gridData = res.data;
      });
    },

    // 新增入库单
    InventoryEntryNewButton() {
      this.newInventoryEntry = true;
    },

    // 批量入库
    storageBulkButton() {
      this.upload.open = true;
      this.fileUploadShow = false;
    },

    // 关闭批量入库
    offUpload() {
      this.fileUploadShow = false;
    },

    //重置
    resetQuery() {
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.createTime = null;
      this.resetForm("queryForm");
      this.inquireList();
    },

    // 选择了时间
    createTimeChange() {
      this.queryParams.beginTime = this.createTime ? this.createTime[0] : null;
      this.queryParams.endTime = this.createTime ? this.createTime[1] : null;
    },

    // 点击查询
    inquireList() {
      this.loading = true;
      const enterpriseId = this.presentEnterprise?.enterpriseId
        ? this.presentEnterprise.enterpriseId
        : null;

      const time = timeComparison(
        180,
        "earching",
        this.queryParams.beginTime,
        this.queryParams.endTime
      );
      if (!time) return (this.loading = false);

      batchlist({ ...this.queryParams, enterpriseId })
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.total = 0;
          this.loading = false;
        });
    },

    // 查询油站
    getStationList() {
      const enterpriseId = this.presentEnterprise?.enterpriseId
        ? this.presentEnterprise.enterpriseId
        : null;
      getRepositoryAndStation({ enterpriseId, status: "1" }).then((res) => {
        this.stationList = res;
        // console.log("油站",res)
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      if (this.selectionList.length) {
        const warehouseBatchList = this.selectionList;

        this.$confirm("请确认是否导出所选入库记录~", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return batchExport(warehouseBatchList);
          })
          .then((response) => {
            this.download(response.msg);
            this.inquireList();
          });
      } else {
        this.$confirm("请先勾选指定入库记录~", "提示", {
          showConfirmButton: false,
          showCancelButton: false,
        });
      }
    },
  },

  watch: {
    newInventoryEntry: {
      deep: true, // 深度监听
      handler(newVal, oldVal) {
        if (oldVal) {
          this.inquireList();
        }
      },
    },
  },
};
</script>
<style scoped lang="scss">
.dialog-footer {
  margin-top: 20px;
}
.dialog-margin {
  margin: 50px 30px 50px 0px;
}

.dialog-div {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-button {
  position: absolute;
  left: 50%;
  bottom: 20px;
}

.dialog-table {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tableInto-table {
  width: 100%;
  height: 350px;
  overflow: auto;
}
</style>
